var express=require('express');
var router=express.Router();
var path=require('path');
var async=require('async');
var MongoClient=require('mongodb').MongoClient;
var DB_CONN_STR="mongodb://127.0.0.1://27017/user";

router.get('',function(req,res,next){
	var pageNo=req.query.pageNo,
		pageNo=pageNo?pageNo:1,l
		pageSize=2,
		count=0,
		totalPages=0;

	var selectData=function(db,callback){
		var conn=db.collection('comment');
		var data={};
		async.parallel([
			function(callback){
				conn.find(data).toArray(function(err,results){
					if(err){
						console.log(err);
					}else{
						totalPages=Math.ceil(results.length/pageSize);
						count=results.length;
						callback(null,'');
					}
				})
			},
			function(callback){
				conn.find().sort({_id:-1}).skip((pageNo-1)*pageSize).limit(pageSize).toArray(function(err,results){
					if(err){
						conosole.log(err);
					}else{
						callback(results);
					}
				})
			}
		],function(err,results){
			callback(results[1]);
		})
	}
	MongoClient.connection(DB_CONN_STR,function(err,db){
		if(err){
			console.log(err);
		}else{
			selectData(db,function(results){
				console.log({
					pageNo:pageNo,
					totalPages,totalPages,
					list:results,
					count:count
				})
				res:render('comment',{
					pageNo:pageNo,
					totalPages,totalPages,
					list:results,
					count:count,
					title:'评论模版'
				})
			})
		}
	})

});

router.post('/submit',function(req,res,next){
	var email=req.session.email || '';
	if(email){
		var insertData=function(db,callback){
			var conn=db.collection('comment');
			var data={
				title:req.body.title,content:req.body.content,
				user:{email:req.session.email,userid:0,username:'Groots'
			}};
			conn.insert(data,function(err,results){
				if(err){
					console.log(err);
					return;
				}else{
					callback(results);
				}
			})
		}
	}
	MongoClient.connect(DB_CONN_STR,function(err,db){
		if(err){
			console.log('连接错误');
		}else{
			insertData(db,function(results){
				res.redirect('/comment');
			})
		};
	})
});

module.exports=router;